package com.tencreat.service.im;

import com.tencreat.common.config.OpenIMConfig;
import com.tencreat.common.core.redis.RedisCache;
import com.tencreat.common.utils.spring.SpringUtils;
import com.tencreat.common.utils.uuid.IdUtils;
import com.tencreat.domain.im.dto.OpenIMTokenDTO;
import com.tencreat.domain.im.vo.OpenIMResultVo;
import com.tencreat.domain.im.vo.OpenIMTokenVo;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CommonFeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 设置请求地址
        OpenIMConfig openIMConfig = OpenIMConfig.getOpenIMConfig();
        template.target(openIMConfig.getUrl());
        // 设置管理员TOKEN
        if (!template.path().equals("/auth/user_token") && !template.headers().containsKey("admin")) {
            RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
            if (!redisCache.hasKey(OpenIMApi.IM_ADMIN_LOGIN_TOKEN)) {
                // 获取openIM管理员token
                OpenIMApi openIMApi = SpringUtils.getBean(OpenIMApi.class);
                OpenIMTokenDTO openIMTokenDTO = new OpenIMTokenDTO(openIMConfig.getSecret(), 5, openIMConfig.getAdminUserId());
                OpenIMResultVo<OpenIMTokenVo> tokenResult = openIMApi.adminToken(openIMTokenDTO);
                if (tokenResult.getErrCode() == 0) {
                    String adminToken = tokenResult.getData().getToken();
                    redisCache.setCacheObject(OpenIMApi.IM_ADMIN_LOGIN_TOKEN, adminToken, Integer.parseInt(tokenResult.getData().getExpireTimeSeconds()) - 3600, TimeUnit.SECONDS);
                    template.header("token", adminToken);
                } else {
                    log.info("获取OpenIM管理员Token失败,{}", tokenResult);
                }
            } else {
                template.header("token", (String) redisCache.getCacheObject(OpenIMApi.IM_ADMIN_LOGIN_TOKEN));
            }
        }
        // 设置链路ID
        template.header("operationID", IdUtils.fastUUID());

    }

    /**
     * 配置Feign日志级别
     *
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }


}